package com.ipnc.dss.util;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;

import com.ipnc.dss.config.Command;
import com.ipnc.dss.config.Config;
import com.ipnc.dss.exception.IPNCException;

/**
 * @author dp
 * 
 */
public class IPNCUtil {

	public static void main(String[] args) {
	}

	public static boolean isOpen(String remoteAddr) {
		try {
			URL url = new URL(remoteAddr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			//
		}
		return false;
	}

	public static String getRemoteIP(IoSession session) {
		String remoteAddr = session.getRemoteAddress().toString().substring(1);
		remoteAddr = remoteAddr.substring(0, remoteAddr.indexOf(":"));
		return remoteAddr;
	}

	public static String formateMacAddr(String macAddr) {
		String fromatMacAddr = macAddr;
		if (macAddr.indexOf("-") != -1) {
			fromatMacAddr = macAddr.replaceAll("-", "");
		}
		return fromatMacAddr.trim();
	}

	public static String getworkingServer(Map<String, Integer> serverBanlance) {
		String workingServer = "";

		Integer minValue = 0;
		int count = 0;
		for (String server : serverBanlance.keySet()) {
			Integer currentValue = serverBanlance.get(server);
			if (count == 0) {
				workingServer = server;
				minValue = currentValue;
			} else {
				if (minValue.compareTo(currentValue) > 0) {
					workingServer = server;
					minValue = currentValue;
				}
			}
			count++;
		}
		return workingServer;
	}

	public static String[] getMessage(String message, String mark) {
		String[] ret = null;
		if (message.lastIndexOf(mark) != 0) {
			String[] temp = message.split(mark);
			ret = new String[temp.length - 1];
			for (int i = 1; i < temp.length; i++) {
				ret[i - 1] = mark + temp[i];
			}
		} else {
			ret = new String[] { message };
		}

		return ret;
	}

	public static Command parseCommand(String command) throws IPNCException {
		if (!StringUtil.isValidString(command)) {
			throw new IPNCException("ommand formate error.");
		}
		return Command.valueOf(command);
	}

	public static String appendData(String command, Map<String, Integer> paras) {
		StringBuffer sb = new StringBuffer();
		sb.append(command);
		sb.append(Config.COMMAND_SPLIT);
		for (String server : paras.keySet()) {
			sb.append(server).append(Config.COMMAND_SPLIT_3)
					.append(paras.get(server)).append(Config.COMMAND_SPLIT_2);
		}
		return sb.toString().trim();
	}

	public static String appendData(String command, String split, String[] paras) {
		StringBuffer sb = new StringBuffer();
		sb.append(command);
		sb.append(Config.COMMAND_SPLIT);
		for (int i = 0; i < paras.length; i++) {
			sb.append(paras[i]).append(split);
		}
		return sb.toString().trim();
	}

	public static void sendTcpJCommand(IoSession session, String message) {
		WriteFuture writeFuture = session.write(message);
		writeFuture.awaitUninterruptibly(Config.WRITE_TIMEOUT);
		writeFuture.addListener(new IoFutureListener<WriteFuture>() {
			public void operationComplete(WriteFuture future) {
				if (future.isWritten()) {
					return;
				}
			}
		});
	}

	public static void sendTcpCCommand(IoSession session, String message) {
		WriteFuture writeFuture = session.write(IPNCUtil
				.string2IoBuffer(message));
		writeFuture.awaitUninterruptibly(Config.WRITE_TIMEOUT);
		writeFuture.addListener(new IoFutureListener<WriteFuture>() {
			public void operationComplete(WriteFuture future) {
				if (future.isWritten()) {
					return;
				}
			}
		});
	}

	public static void sendUdpJCommand(IoSession session, String message) {
		WriteFuture writeFuture = session.write(message);
		writeFuture.awaitUninterruptibly(Config.WRITE_TIMEOUT);
		writeFuture.addListener(new IoFutureListener<WriteFuture>() {
			public void operationComplete(WriteFuture future) {
				if (future.isWritten()) {
					return;
				}
			}
		});
	}

	public static void sendUdpCCommand(IoSession session, String message) {
		WriteFuture writeFuture = session.write(IPNCUtil
				.string2IoBuffer(message));
		writeFuture.awaitUninterruptibly(Config.WRITE_TIMEOUT);
		writeFuture.addListener(new IoFutureListener<WriteFuture>() {
			public void operationComplete(WriteFuture future) {
				if (future.isWritten()) {
					return;
				}
			}
		});
	}

	public static void sendUdpData(IoSession session, byte[] byteData) {
		int size = byteData.length;
		if (size > Config.PACKET_SIZE) {
			int j = 0;
			byte[] tData = new byte[Config.PACKET_SIZE];
			for (int i = 0; i < size; i++) {
				tData[j++] = byteData[i];
				if (j == Config.PACKET_SIZE - 1) {
					j = 0;
					session.write(byteArray2IoBuffer(tData));
				}
			}
			session.write(byteArray2IoBuffer(tData));
		} else {
			session.write(byteArray2IoBuffer(byteData));
		}
	}

	public static String appendCommand(String command, String[] paras) {
		StringBuffer sb = new StringBuffer();
		sb.append(command).append(Config.COMMAND_SPLIT);
		for (int i = 0; i < paras.length; i++) {
			sb.append(paras[i]).append(Config.COMMAND_SPLIT);
		}
		return sb.toString().trim();
	}

	public static String appendCommand(String command, String para) {
		StringBuffer sb = new StringBuffer();
		sb.append(command).append(Config.COMMAND_SPLIT).append(para);
		return sb.toString();
	}

	// public static byte[] ioBuffer2ByteArray(IoBuffer ioBuffer) {
	// byte[] byteBuf = new byte[ioBuffer.limit()];
	// ioBuffer.get(byteBuf);
	// return byteBuf;
	// }

	public static byte[] ioBuffer2ByteArray(IoBuffer ioBuffer) {
		byte[] byteBuf = new byte[ioBuffer.limit()];
		int pos = ioBuffer.position();
		ioBuffer.rewind();
		ioBuffer.get(byteBuf);
		ioBuffer.position(pos);
		return byteBuf;
	}

	public static IoBuffer byteArray2IoBuffer(byte[] byteArray) {
		IoBuffer ioBuffer = IoBuffer.allocate(byteArray.length);
		ioBuffer.put(byteArray);
		ioBuffer.flip();
		return ioBuffer;
	}

	public static void byteArray2IoBuffer(byte[] byteArray, IoBuffer ioBuffer) {
		ioBuffer.put(byteArray);
		ioBuffer.flip();
	}

	public static IoBuffer string2IoBuffer(String str) {
		byte[] byteArray = StringUtil.string2Byte(str);
		IoBuffer ioBuffer = IoBuffer.allocate(byteArray.length);
		ioBuffer.put(byteArray);
		ioBuffer.flip();
		return ioBuffer;
	}

	public static String ioBuffer2String(IoBuffer ioBuffer) {
		byte[] byteBuf = ioBuffer.array();
		return StringUtil.byte2String(byteBuf);
	}

	public static void byteArray2File(File file, byte[] bytes) {
		try {
			FileUtils.writeByteArrayToFile(file, bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
